using System.ComponentModel;
using System.Text.RegularExpressions;

namespace Altairis.Web.UI.WebControls {

    public class HostNameLabel : System.Web.UI.WebControls.Label {
        private const string DEFAULT_ANONYMIZE_STRING = "---";

        public HostNameLabel() {
            this.AnonymizeString = DEFAULT_ANONYMIZE_STRING;
        }

        [Category("Behavior"), DefaultValue(DEFAULT_ANONYMIZE_STRING), Description("Specifies string displayed instead of anonymized part of name/IP. If null or empty, name is not anonymized.")]
        public string AnonymizeString { get; set; }

        protected override void Render(System.Web.UI.HtmlTextWriter writer) {
            if (!string.IsNullOrEmpty(this.Text) && !string.IsNullOrEmpty(this.AnonymizeString)) {
                if (Regex.IsMatch(this.Text, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")) {
                    // It's IP address - anonymize last part
                    string[] parts = this.Text.Split('.');
                    parts[3] = this.AnonymizeString;
                    this.Text = string.Join(".", parts);
                }
                else if (this.Text.IndexOf('.') > -1) {
                    // It's Internet hostname - anonymize first part
                    string[] parts = this.Text.Split('.');
                    parts[0] = this.AnonymizeString;
                    this.Text = string.Join(".", parts);
                }
            }
            base.Render(writer);
        }
    }
}